package uit.minito.suggestion;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import uit.minito.timduongxebuyt.R;
import uit.minito.timduongxebuyt.StaticVariables;
import uit.minito.views.MyUtilities;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

public class SuggestionAdapter extends ArrayAdapter<SuggestionModel> implements Filterable{
	private List<SuggestionModel> dataList=new ArrayList<SuggestionModel>();
	private static SuggestionModel[] demoArray={null,null};
	private LayoutInflater inflater;
	public SuggestionAdapter(Context context){
		super(context, 0, demoArray);
		inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
	}
	public void updateData(ArrayList<SuggestionModel> _data){
		//dataList=_data;
		//this.notifyDataSetChanged();
		dataList.clear();
		
		for(int i=0;i<_data.size();i++){
			dataList.add(_data.get(i));
		}
		notifyDataSetChanged();
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View resultView=convertView;
		SuggestionModel currentModel=dataList.get(position);
		if(currentModel!=null){
			resultView=inflater.inflate(R.layout.suggestion_cell,null);
			TextView cellTextView=(TextView)resultView.findViewById(R.id.suggestionCellTextView);
			if(cellTextView!=null){
				cellTextView.setText(currentModel.getAddress());
			}
		}
		return resultView;
	}
	@Override
	public Filter getFilter() {
		// TODO Auto-generated method stub
		Filter myFilter=new Filter() {
			
			@Override  
			protected void publishResults(CharSequence constraint, FilterResults results) {
				// TODO Auto-generated method stub
				
					if(results!=null && results.count!=0){
						if(constraint.length()>=StaticVariables.AUTOTEXTVIEW_MAX_THRESHOLD){
							//updateData(new ArrayList<SuggestionModel>());
							dataList.clear();
							notifyDataSetChanged();
						}else{ 
							updateData((ArrayList<SuggestionModel>)results.values);
						}
						
						
					}else{
						notifyDataSetInvalidated();
					}  
				
				
			}
			  
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				// TODO Auto-generated method stub
				FilterResults filterResults=new FilterResults();
				ArrayList<SuggestionModel> resultList=new ArrayList<SuggestionModel>();
				if(constraint!=null){
					try {
						//fetch Data here
						
						String inputText=constraint.toString();
						//replace all SPACE character with plus sign
						HttpClient httpClient=new DefaultHttpClient();
						InputStream inputStream=null;
						String fetchedString=null;
						StringBuilder stringBuilder=null;
						
						String fetchQuery=StaticVariables.GOOGLE_PLACES_API+inputText;
						String correctFormatQuery=MyUtilities.convertURL(fetchQuery);
						
							//Request and get the Response
							HttpResponse response=httpClient.execute(new HttpGet(correctFormatQuery));
							//the put to an inputStream
							inputStream=response.getEntity().getContent();
							//create a reader to read that inputStream
							BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
							//a stringbuilder to combine each line of the inputStream
							stringBuilder=new StringBuilder();
							//begin to read
							String line=null;
							while((line=reader.readLine())!=null){
								stringBuilder.append(line+"\n");
							}
							//after finish reading, we close the inputStream
							inputStream.close();
							//got the fetchedString from the builder
							fetchedString=stringBuilder.toString();
							//parse JSON and store to our Model
							SuggestionJSONParser jsonParser=new SuggestionJSONParser();
							resultList=jsonParser.parse(fetchedString);
					} catch (Exception e) {
						// TODO: handle exception
						Log.i(StaticVariables.DEBUG_TAG, "SuggestionAdapter >> publishResults");
					}
					filterResults.values=resultList;
					filterResults.count=resultList.size();
					
				}
				return filterResults;
			}
		};
		return myFilter;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return dataList.size();
	}
	@Override
	public SuggestionModel getItem(int position) {
		// TODO Auto-generated method stub
		return dataList.get(position);
	}

	public SuggestionAdapter(Context context, int textViewResourceId) {
		super(context, textViewResourceId);
		// TODO Auto-generated constructor stub
	}

}
